<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
    <style>
        .file-input-label:hover {
            background-color: #f3f4f6;
        }

        .file-input-label:active {
            background-color: #e5e7eb;
        }

        .preview-image {
            transition: all 0.3s ease;
        }

        .preview-image:hover {
            transform: scale(1.05);
        }

        .error-message {
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .error-message.show {
            opacity: 1;
        }
    </style>
</head>
<body class="bg-gray-50">
<div class="container mx-auto px-4 py-8 max-w-4xl">
    <div class="bg-white rounded-xl shadow-md overflow-hidden p-6 mb-8">
        <div class="flex items-center justify-between mb-6">
            <h1 class="text-2xl font-bold text-gray-800">
                <span th:if="${goods.id == null}">添加新商品</span>
                <span th:unless="${goods.id == null}">编辑商品</span>
            </h1>
            <a href="/manage?page=1&pageSize=5" class="text-blue-600 hover:text-blue-800 flex items-center">
                <i class="fas fa-arrow-left mr-2"></i> 返回列表
            </a>
        </div>

        <form th:action="${goods.id == null} ? '/goods/add' : '/goods/edit'" th:object="${goods}" method="post"
              enctype="multipart/form-data" class="space-y-6" onsubmit="return validateForm()">
            <input type="hidden" th:if="${goods != null}" th:field="*{id}">

            <!-- 商品名称 -->
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700 mb-1">商品名称 *</label>
                <input type="text" id="name" th:field="*{title}"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                       placeholder="请输入商品名称" required>
                <div id="name-error" class="error-message text-red-500 text-sm mt-1">请输入商品名称</div>
            </div>

            <!-- 描述 -->
            <div>
                <label for="description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                <textarea id="description" th:field="*{descr}" rows="3"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                          placeholder="请输入商品描述"></textarea>
            </div>

            <!-- 价格 -->
            <div>
                <label for="price" class="block text-sm font-medium text-gray-700 mb-1">价格 *</label>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <span class="text-gray-500">￥</span>
                    </div>
                    <input type="number" id="price" th:field="*{price}" step="0.01" min="0"
                           class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition"
                           placeholder="0.00" required>
                </div>
                <div id="price-error" class="error-message text-red-500 text-sm mt-1">请输入有效的价格</div>
            </div>

            <!-- 商品图片 -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">商品图片</label>
                <div class="mt-1 flex items-center space-x-4">
                    <label for="image"
                           class="file-input-label cursor-pointer flex flex-col items-center justify-center px-4 py-6 bg-white border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-500 transition">
                        <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                        <span class="text-sm text-gray-600">点击上传</span>
                        <span class="text-xs text-gray-500">PNG, JPG, JPEG (最大 5MB)</span>
                        <input id="image" name="image" type="file" class="hidden" accept="image/*"
                               onchange="previewImage(event)">
                        <input type="hidden" id="img-url" name="img" th:field="*{img}">
                    </label>
                    <div id="image-preview" class="hidden">
                        <div class="relative">
                            <img id="preview" src="#" alt="预览"
                                 class="h-24 w-24 object-cover rounded-lg preview-image">
                            <button type="button" onclick="removeImage()"
                                    class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600 transition">
                                <i class="fas fa-times text-xs"></i>
                            </button>
                        </div>
                    </div>
                    <div th:if="${goods != null && goods.img != null}" class="relative">
                        <img th:src="${goods.img}" alt="当前图片"
                             class="h-24 w-24 object-cover rounded-lg preview-image">
                        <div class="text-xs text-gray-500 mt-1">当前图片</div>
                    </div>
                </div>
            </div>

            <!-- 状态 -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <div class="flex items-center space-x-4">
                    <label class="inline-flex items-center">
                        <input type="radio" th:field="*{state}" value="0"
                               class="h-4 w-4 text-blue-600 focus:ring-blue-500">
                        <span class="ml-2 text-gray-700">上架</span>
                    </label>
                    <label class="inline-flex items-center">
                        <input type="radio" th:field="*{state}" value="1"
                               class="h-4 w-4 text-blue-600 focus:ring-blue-500">
                        <span class="ml-2 text-gray-700">下架</span>
                    </label>
                </div>
            </div>

            <!-- 按钮 -->
            <div class="flex justify-end space-x-4 pt-6 border-t border-gray-200">
                <button type="button" onclick="window.location.href='/manage?page=1&pageSize=5'"
                        class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                    取消
                </button>
                <button type="submit"
                        class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition">
                    <span th:if="${goods.id == null}">添加商品</span>
                    <span th:unless="${goods.id == null}">更新商品</span>
                </button>
            </div>
        </form>
    </div>
</div>
</body>
</html>

<script>
    const client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
        region: "oss-cn-beijing",
        authorizationV4: true,
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: "LTAI5t8Mq4ohY81YCczMaYg1",
        accessKeySecret: "r2BBbNWkjDTGLLHxLaxbDahfv8DTfV",
        // 从STS服务获取的安全令牌（SecurityToken）。
        // stsToken: "yourSecurityToken",
        // 填写Bucket名称。
        bucket: "ccibe-ep",
    });

    let data;

    async function putObject(data) {
        try {
            // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
            // 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
            // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
            const options = {
                meta: {temp: "demo"},
                mime: "json",
                headers: {"Content-Type": "text/plain"},
            };
            const result = await client.put(`${new Date().getTime()}.png`, data, options);

            console.log(result.url);
            document.getElementById('img-url').value = result.url;
        } catch (e) {
            console.log(e);
        }
    }

    // Form validation
    function validateForm() {
        let isValid = true;

        // Validate name
        const name = document.getElementById('name').value.trim();
        if (!name) {
            document.getElementById('name-error').classList.add('show');
            isValid = false;
        } else {
            document.getElementById('name-error').classList.remove('show');
        }

        // Validate price
        const price = document.getElementById('price').value;
        if (!price || isNaN(price) || parseFloat(price) <= 0) {
            document.getElementById('price-error').classList.add('show');
            isValid = false;
        } else {
            document.getElementById('price-error').classList.remove('show');
        }

        // Validate stock
        // const stock = document.getElementById('stock').value;
        // if (!stock || isNaN(stock) || parseInt(stock) < 0) {
        //     document.getElementById('stock-error').classList.add('show');
        //     isValid = false;
        // } else {
        //     document.getElementById('stock-error').classList.remove('show');
        // }

        // Validate category
        // const category = document.getElementById('category').value;
        // if (!category) {
        //     document.getElementById('category-error').classList.add('show');
        //     isValid = false;
        // } else {
        //     document.getElementById('category-error').classList.remove('show');
        // }

        return isValid;
    }

    // Image preview functionality
    function previewImage(event) {
        const input = event.target;
        const previewContainer = document.getElementById('image-preview');
        const preview = document.getElementById('preview');

        if (input.files && input.files[0]) {
            const reader = new FileReader();

            reader.onload = function (e) {
                preview.src = e.target.result;
                previewContainer.classList.remove('hidden');
            }

            reader.readAsDataURL(input.files[0]);
        }

        putObject(input.files[0]);
    }

    function removeImage() {
        const input = document.getElementById('image');
        const previewContainer = document.getElementById('image-preview');

        input.value = '';
        previewContainer.classList.add('hidden');
    }

    // Initialize error messages to show if fields are invalid on blur
    document.getElementById('name').addEventListener('blur', function () {
        if (!this.value.trim()) {
            document.getElementById('name-error').classList.add('show');
        }
    });

    document.getElementById('price').addEventListener('blur', function () {
        if (!this.value || isNaN(this.value) || parseFloat(this.value) <= 0) {
            document.getElementById('price-error').classList.add('show');
        }
    });

    // document.getElementById('stock').addEventListener('blur', function () {
    //     if (!this.value || isNaN(this.value) || parseInt(this.value) < 0) {
    //         document.getElementById('stock-error').classList.add('show');
    //     }
    // });

    // document.getElementById('category').addEventListener('change', function () {
    //     if (!this.value) {
    //         document.getElementById('category-error').classList.add('show');
    //     } else {
    //         document.getElementById('category-error').classList.remove('show');
    //     }
    // });
</script>
</body>
</html>